package edu.ptu.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.ptu.acl.common.AdminValidate;
import edu.ptu.acl.common.RequestHolder;
import edu.ptu.acl.entity.Role;
import edu.ptu.acl.entity.RoleAcl;
import edu.ptu.acl.entity.RoleUser;
import edu.ptu.acl.entity.User;
import edu.ptu.acl.exception.ApiException;
import edu.ptu.acl.mapper.RoleAclMapper;
import edu.ptu.acl.mapper.RoleMapper;
import edu.ptu.acl.mapper.RoleUserMapper;
import edu.ptu.acl.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LinJC
 * @since 2022-03-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleUserMapper roleUserMapper;
    @Resource
    private RoleAclMapper roleAclMapper;

    @Override
    public void deleteRole(Long roleId) {
        roleMapper.deleteById(roleId);

        QueryWrapper<RoleAcl> roleAclQueryWrapper = new QueryWrapper<>();
        roleAclQueryWrapper.eq("role_id",roleId);
        roleAclMapper.delete(roleAclQueryWrapper);

        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        roleUserQueryWrapper.eq("role_id",roleId);
        roleUserMapper.delete(roleUserQueryWrapper);

    }

    @Override
    public void validateName(Long parentId, Long id,String name) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("parent_id",parentId);
        roleQueryWrapper.eq("name",name);
        roleQueryWrapper.ne("id",id);
        if (roleMapper.selectCount(roleQueryWrapper)!=0) {
            throw new ApiException("重名了");
        }
    }

    @Override
    public List<Role> getCurrentUserRoles() {
        User currentUser = RequestHolder.getCurrentUser();
        if (AdminValidate.isAdmin()){
            return roleMapper.selectList(null);
        }
        Long userId = currentUser.getId();
        QueryWrapper<RoleUser> roleUserQueryWrapper = new QueryWrapper<>();
        roleUserQueryWrapper.eq("user_id",userId);
        List<RoleUser> allRoleUsers = roleUserMapper.selectList(roleUserQueryWrapper);
        Set<Long> roleIds = allRoleUsers.stream().map(RoleUser::getRoleId).collect(Collectors.toSet());
        List<Role> roles = roleMapper.selectBatchIds(roleIds);
        // 去除冻结中的角色
        List<Role> normalRoles = roles.stream().filter(role -> StringUtils.equals(role.getStatus(), "1")).collect(Collectors.toList());
        return normalRoles;
    }
}
